package cn.meomis.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import cn.meomis.common.entity.Pagination;
import cn.meomis.common.util.Constant;
import cn.meomis.common.util.DataTableParam;
import cn.meomis.model.Che;
import cn.meomis.model.SysLog;
import cn.meomis.model.Value;
import cn.meomis.model.ValueDetail;
import cn.meomis.service.CheService;
import cn.meomis.service.SysLogService;
import cn.meomis.service.ValueDetailService;
import cn.meomis.service.ValueService;

//@Scope("prototype") 
@Controller
//@Namespace("/")
@ParentPackage("json-default")
//@Result(name="success", type="json")
public class ValueDetailAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private ValueDetail valueDetail;
	
	// @Resource
	@Autowired
	private ValueDetailService valueDetailService;
	@Autowired
	private CheService cheService;
	
	@Autowired
	private ValueService valueService;
	
	@Autowired
	private SysLogService sysLogService;		//日志

	
	@Action(value = "/valueDetailAction", results = { @Result(name = SUCCESS, location = "/manager/modules/valueDetail/valueDetail.jsp")})
	@Override
	public String execute() {
/*		String type = httpServletRequest.getParameter("type");
		List<Demo> demoList = valueService.findAll();
		httpServletRequest.setAttribute("DEMO_LIST", demoList);
		if ("manager".equals(type)) {
			return "manager";
		}*/
		List<Che> cheList = cheService.findAll();
		httpServletRequest.setAttribute("CHE_LIST", cheList);
		return SUCCESS;
	}
	
	@Action(value = "/findvalueDetailAction", results = { @Result(name = SUCCESS, location = "/manager/modules/valueDetail/edit.jsp") })
	public String find(){
		ValueDetail valueDetailInstance = valueDetailService.findById(Integer.parseInt(httpServletRequest.getParameter("id")));
		httpServletRequest.setAttribute("valueDetailInstance", valueDetailInstance);
		List<Che> cheList = cheService.findAll();
		httpServletRequest.setAttribute("CHE_LIST", cheList);
		return SUCCESS;
	}

	@Action(value = "/valueDetailEditAction", results = { @Result(name = SUCCESS, location = "/valueDetailAction.action", type = "redirect") })
	public String cheEdit() throws UnsupportedEncodingException {
		ValueDetail valueDetailInstance = valueDetailService.findById(valueDetail.getId());
		valueDetailInstance.setCreatetime(new Date());
		valueDetailInstance.setCheId(valueDetail.getCheId());
		valueDetailInstance.setValuedetail(valueDetail.getValuedetail());

		valueDetailService.save(valueDetailInstance);
		return SUCCESS;
	}
	
	@Action(value = "/valueBackupsAction", results=@Result(name="success", type="json"))
	public void valueBackupsAction() throws IOException {
		String result = "success";
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();
		
		try {
			
			String ids = httpServletRequest.getParameter("id");
			
//			if(!"".equals(httpServletRequest.getParameter("id"))){
//				
//			}
			for(String id : ids.split(",")){
				int valueId = Integer.parseInt(id);
			
				DetachedCriteria detachedCriteriaValue = DetachedCriteria.forClass(Value.class);
				detachedCriteriaValue.add(Restrictions.eq("id", valueId));
	//			detachedCriteriaValue.add(Restrictions.eq("backupsState", Constant.VALUEDETAILNOTBACKUPS));
				
				List<Value> listValues = valueService.queryList(detachedCriteriaValue);
	//			Date currentDate = new Date();
				for(Value vd : listValues){
					
					try {
						SysLog sl = new SysLog();
						sl.setContent("备份车属性值,属性名["+vd.getTypename()+"],车类型,名称["+cheService.findById(vd.getCheId()).getName()+"],备份前阀门值["+vd.getGrandTotalValue()+"]");
						sl.setCreateDate(new Date());
						sysLogService.save(sl);
					} catch (Exception e) {

						e.printStackTrace();
					}
					
					vd.setGrandTotalValue(0);
					//				vd.setBackupsState(Constant.VALUEDETAILISBACKUPS);
					//				vd.setBackupsTime(currentDate);
					valueService.save(vd);
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result = "error";
		}
		
		jsonResponse.put("isSorF", result);
		httpServletResponse.getWriter().print(jsonResponse.toString());

	}
	
	
	/*@Action(value = "/valueDetailBackupsAction", results=@Result(name="success", type="json"))
	public void valueDetailBackups() throws IOException {
		String result = "success";
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();
		
		try {
			int cheId = Integer.parseInt(httpServletRequest.getParameter("id"));
			DetachedCriteria detachedCriteriaValue = DetachedCriteria.forClass(ValueDetail.class);
			detachedCriteriaValue.add(Restrictions.eq("cheId", cheId));
			detachedCriteriaValue.add(Restrictions.eq("backupsState", Constant.VALUEDETAILNOTBACKUPS));
			
			List<ValueDetail> listValueDetails = valueDetailService.queryList(detachedCriteriaValue);
			Date currentDate = new Date();
			for(ValueDetail vd : listValueDetails){
				vd.setBackupsState(Constant.VALUEDETAILISBACKUPS);
				vd.setBackupsTime(currentDate);
				valueDetailService.save(vd);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result = "error";
		}
		
		jsonResponse.put("isSorF", result);
		httpServletResponse.getWriter().print(jsonResponse.toString());

	}*/
	
	@Action(value="/valueDetailAddAction",results=@Result(name="success", type="json"))
	public void addNotice() throws IOException{
		String result = "success";
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();
		
		//先保存数据
		try {
			valueDetail.setCreatetime(new Date());
			valueDetailService.save(valueDetail);
			
			try {
				SysLog sl = new SysLog();
				sl.setContent("添加车属性值,累计值["+valueDetail.getValuedetail()+"],车类型,名称["+cheService.findById(valueDetail.getCheId()).getName()+"]");
				sl.setCreateDate(new Date());
				sysLogService.save(sl);
			} catch (Exception e) {

				e.printStackTrace();
			}
			
		} catch (Exception e1) {
			e1.printStackTrace();
			result = "error";
			jsonResponse.put("isSorF", result);
			httpServletResponse.getWriter().print(jsonResponse.toString());
			return;
		}
		
		
		//然后进行累加值和阀门值比较
		Che che = cheService.findById(valueDetail.getCheId());
		DetachedCriteria detachedCriteriaValue = DetachedCriteria.forClass(ValueDetail.class);
		detachedCriteriaValue.add(Restrictions.eq("cheId", valueDetail.getCheId()));
		detachedCriteriaValue.add(Restrictions.eq("backupsState", Constant.VALUEDETAILNOTBACKUPS));
		
		//查询 累计输入值是否大于阀门值。
		List<ValueDetail> listValueDetails = valueDetailService.queryList(detachedCriteriaValue);
		
		String valueId = "";		// valueId
		String returnMessage = "";	//返回的错误消息
		if(listValueDetails.size() > 0){	
			//int i = valueDetail.getValuedetail();	//累计输入值表的值
			int i = 0;
			//计算 累计输入值
			for(ValueDetail vd : listValueDetails){
				i = i + vd.getValuedetail();
			}
			
			DetachedCriteria detachedCriteria_value = DetachedCriteria.forClass(Value.class);
			detachedCriteria_value.add(Restrictions.eq("cheId", valueDetail.getCheId()));
			List<Value> vaList = valueService.queryList(detachedCriteria_value);
			
			for(Value va : vaList){
				va.setGrandTotalValue(va.getGrandTotalValue()+valueDetail.getValuedetail());		//更新属性表的累加值,当前值+输入的值
				valueService.save(va);
//			}
//			for(Value va : vaList){
				if(va.getGrandTotalValue() > va.getValue()){
					valueId = valueId + va.getId() + ",";
					returnMessage = returnMessage + che.getName()+ " 阀门值  "+va.getTypename()+"("+va.getValue()+") 当前累加值("+i+"), ";
//					jsonResponse.put("cheId", valueDetail.getCheId());
//					jsonResponse.put("valueId", va.getId());
//					jsonResponse.put("isSorF", "您输入的累计值已经触发到  " +che.getName()+ " 阀门值  "+va.getTypename()+"("+va.getValue()+") 当前累加值("+i+")");
//					httpServletResponse.getWriter().print(jsonResponse.toString());
//					return ;
//					break;
				}
			}
		}
		
		if(!"".equals(valueId)){
			valueId = valueId.substring(0, valueId.length()-1);
			result = returnMessage;
		}
		
		try {
			jsonResponse.put("isSorF", result);
			jsonResponse.put("valueId", valueId);
//			jsonResponse.put("message", returnMessage);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
/*	//判断输入的累计值是否到达标准
	private Boolean checkValue(){
		return null;
		
	}*/

	@Action(value = "/valueDetailDeleteAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect") })
	public String delete() {
		int id = Integer.parseInt(httpServletRequest
				.getParameter("id"));
		try {
			SysLog sl = new SysLog();
			sl.setContent("删除车属性值,阀门值["+valueDetailService.findById(id).getValuedetail()+"],车类型,名称["+cheService.findById(valueDetailService.findById(id).getCheId()).getName()+"]");
			sl.setCreateDate(new Date());
			sysLogService.save(sl);
		} catch (Exception e) {

			e.printStackTrace();
		}
		
		ValueDetail v = valueDetailService.findById(id);		//查询到车属性累计值
		int cheid = 0;		//cheid
		int vd = 0;			//要删除的累计值
		if(null != v){
			cheid = v.getCheId();
			vd = v.getValuedetail();
		}
		
		DetachedCriteria detachedCriteria_value = DetachedCriteria.forClass(Value.class);
		detachedCriteria_value.add(Restrictions.eq("cheId", cheid));
		List<Value> vaList = valueService.queryList(detachedCriteria_value);
		for(Value va : vaList){
			va.setGrandTotalValue(va.getGrandTotalValue()-vd);		//更新属性表的累加值,当前值-输入的值
			valueService.save(va);
		}
		
//		valueDetailService.findById(id).getCheId();
		
		valueDetailService.removeById(id);
		
		
		return SUCCESS;
	}
	
	
	@Action(value = "/valueDetailDelete", results = @Result(name = "success", type = "json"))
	public void deleteDestination(){
		String reslut = "success";
		try {
			int id = Integer.parseInt(httpServletRequest
					.getParameter("id"));
			
			try {
				SysLog sl = new SysLog();
				sl.setContent("删除车属性值,阀门值["+valueDetailService.findById(id).getValuedetail()+"],车类型,名称["+cheService.findById(valueDetailService.findById(id).getCheId()).getName()+"]");
				sl.setCreateDate(new Date());
				sysLogService.save(sl);
			} catch (Exception e) {

				e.printStackTrace();
			}
			
			ValueDetail v = valueDetailService.findById(id);		//查询到车属性累计值
			int cheid = 0;		//cheid
			int vd = 0;			//要删除的累计值
			if(null != v){
				cheid = v.getCheId();
				vd = v.getValuedetail();
			}
			
			DetachedCriteria detachedCriteria_value = DetachedCriteria.forClass(Value.class);
			detachedCriteria_value.add(Restrictions.eq("cheId", cheid));
			List<Value> vaList = valueService.queryList(detachedCriteria_value);
			for(Value va : vaList){
				va.setGrandTotalValue(va.getGrandTotalValue()-vd);		//更新属性表的累加值,当前值-输入的值
				valueService.save(va);
			}
			
			valueDetailService.removeById(id);
			
		} catch (Exception e1) {
			e1.printStackTrace();
			reslut = "failure";
		}

		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", reslut);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@SuppressWarnings({ "unchecked" })
	@Action(value="/valueDetailListAction")
	public void listDestination() {

		DataTableParam params = null;
		try {
			params = getParam();
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		HashMap<String, String> paramMap = convertToMap(params.getVoList());	
		String sEcho = paramMap.get("sEcho");
		Long iTotalRecords; // total number of records (unfiltered)
		Long iTotalDisplayRecords; //value will be set when code filters companies by keyword
		JSONArray data = new JSONArray(); //data that will be shown in the table

		int pageNumber = (Integer.parseInt(paramMap.get("iDisplayStart")) / Integer.parseInt(paramMap.get("iDisplayLength"))) + 1;

		StringBuffer hql =new StringBuffer( "from ValueDetail demo ");
		if (params.getIsQuery().equalsIgnoreCase("true")) {
			hql.append(" where 1 = 1 ");
			String cheId = paramMap.get("cheId").trim();
			String backupsState = paramMap.get("backupsState").trim();
			if (!"".equalsIgnoreCase(cheId)) {
				hql.append(" and demo.cheId = "+cheId+" ");
			}
			
			if (!"".equalsIgnoreCase(backupsState)) {
				hql.append(" and demo.backupsState = "+backupsState+" ");
			}
		}
		
		String sCol = paramMap.get("iSortCol_0");
		String sortingColName =  paramMap.get("mDataProp_"+sCol);
		//asc or desc
	    String sdir = paramMap.get("sSortDir_0");
	   
	    if("0".equals(sortingColName)){
//	    	sortingColName = "dest.destination";
	    }else if("1".equals(sortingColName)){
	    	sortingColName = "demo.valuedetail";
	    }else if("3".equals(sortingColName)){
	    	sortingColName = "demo.createtime";
	    }else if("4".equals(sortingColName)){
	    	sortingColName = "demo.backupsState";
	    }else if("5".equals(sortingColName)){
	    	sortingColName = "demo.backupsTime";
	    }
	    
    	if ("desc".equalsIgnoreCase(sdir)) {
	    	hql.append(" order by "+sortingColName +" desc");
	    }else{
	    	hql.append(" order by "+sortingColName );
	    }
	    

		Object[] values = null;
		Pagination pageMqDestination = valueDetailService.pageQueryByHql(hql.toString(), values, hql.toString(), pageNumber, Integer.parseInt(paramMap.get("iDisplayLength")));
		iTotalRecords = pageMqDestination.getTotalCount();
		List<ValueDetail> companies = (List<ValueDetail>) pageMqDestination.getResult();
//		List<Value> companies = new LinkedList<Demo>();
//		for(Demo c : apps){
//			companies.add(c);
//		}
		
		iTotalDisplayRecords = pageMqDestination.getTotalCount();

	
		try {
			JSONObject jsonResponse = new JSONObject();			
			jsonResponse.put("sEcho", sEcho);
			jsonResponse.put("iTotalRecords", iTotalRecords);
			jsonResponse.put("iTotalDisplayRecords", iTotalDisplayRecords);
			int i = 1;
			for(ValueDetail c : companies){
				Che che = cheService.findById(c.getCheId());
				String cheName = "";
				if(null != che){
					cheName = che.getName();
				}
				JSONArray row = new JSONArray();
				row.put(i++);
				row.put(c.getValuedetail());
//				row.put(c.getTypename());
				row.put(cheName);
				row.put(dateformat.format(c.getCreatetime()));
				row.put(c.getBackupsState() == 0 ? "未备份" : "已备份");
				if(null == c.getBackupsTime()){
					row.put("");
				}else{
					row.put(dateformat.format(c.getBackupsTime()));
				}
				
				row.put(c.getId());
				data.put(row);
			}
			jsonResponse.put("resultList", data);
			httpServletResponse.setContentType("application/Json;charset=utf-8");
			httpServletResponse.getWriter().print(jsonResponse.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			httpServletResponse.setContentType("text/html");
			try {
				httpServletResponse.getWriter().print(e.getMessage());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	public ValueDetail getValueDetail() {
		return valueDetail;
	}

	public void setValueDetail(ValueDetail valueDetail) {
		this.valueDetail = valueDetail;
	}
	
}
